package com.zmc.order.infrastructure.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zmc.common.utils.PageUtils;
import com.zmc.common.utils.StringUtils;
import com.zmc.common.utils.token.AuthTokenService;
import com.zmc.order.infrastructure.bean.query.OrderManageQuery;
import com.zmc.order.infrastructure.entity.OrderItemEntity;
import com.zmc.order.infrastructure.service.OrderItemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.zmc.order.infrastructure.dao.OrderDao;
import com.zmc.order.infrastructure.entity.OrderEntity;
import com.zmc.order.infrastructure.service.OrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * @author zmc
 */
@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private AuthTokenService authTokenService;

    @Autowired
    private OrderItemService orderItemService;

    public static String upLoadPrefix = "http://localhost:8080/api";


    @Override
    public OrderEntity getByOrderSn(String orderNo) {
        LambdaQueryWrapper<OrderEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderEntity::getOrderSn, orderNo);
        return getOne(wrapper);
    }

    @Override
    public PageUtils pageList(OrderManageQuery query) {
        Page<OrderEntity> page = baseMapper.selectPage(new Page<>(query.getPageNum(), query.getPageSize()), getWrapper(query));
        List<OrderEntity> records = page.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            List<String> orderSns = records.stream().map(OrderEntity::getOrderSn).collect(Collectors.toList());
            List<OrderItemEntity> items = orderItemService.listByOrderSns(authTokenService.getMemberInfo().getMemberId(), orderSns);
            //todo 后期转阿里云oss服务，删除可删除此代码
            Map<String, List<OrderItemEntity>> childItems = items.stream()
                    .peek(item-> {
                        String skuPic = item.getSkuPic();
                        item.setSkuPic(upLoadPrefix + skuPic);
                    }).collect(Collectors.groupingBy(OrderItemEntity::getOrderSn));
            records.forEach(orderEntity -> {
                List<OrderItemEntity> list = childItems.get(orderEntity.getOrderSn());
                if (!CollectionUtils.isEmpty(list)) {
                    orderEntity.setItems(list);
                }
            });
        }
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void updateStatus(String orderSn, Integer status) {
        LambdaUpdateWrapper<OrderEntity> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(OrderEntity::getOrderSn, orderSn)
                .set(OrderEntity::getStatus, status);
        update(wrapper);
    }

    @Override
    @Transactional
    public void updateOrderWhenSendGood(String orderSn, Integer status) {
        LambdaUpdateWrapper<OrderEntity> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(OrderEntity::getOrderSn, orderSn)
                .set(OrderEntity::getStatus, status)
                .set(OrderEntity::getDeliveryTime, LocalDateTime.now());
        update(wrapper);
    }

    @Override
    @Transactional
    public void updateOrderWhenReceive(String orderSn, Integer status, Integer confirmStatus) {
        LambdaUpdateWrapper<OrderEntity> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(OrderEntity::getOrderSn, orderSn)
                .set(OrderEntity::getStatus, status)
                .set(OrderEntity::getConfirmStatus, confirmStatus)
                .set(OrderEntity::getReceiveTime, LocalDateTime.now());
        update(wrapper);
    }

    @Override
    @Transactional
    public void updateOrderWhenDelivery(String orderSn, Integer status) {
        LambdaUpdateWrapper<OrderEntity> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(OrderEntity::getOrderSn, orderSn)
                .set(OrderEntity::getStatus, status)
                .set(OrderEntity::getDeliveryTime, LocalDateTime.now());
        update(wrapper);
    }

    @Override
    public OrderEntity getLastWaitPayOrder() {
        LambdaUpdateWrapper<OrderEntity> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(OrderEntity::getMemberId, authTokenService.getMemberInfo().getMemberId())
                .orderByDesc(OrderEntity::getCreateTime).last(" limit 1");
        return getOne(wrapper);
    }

    @Override
    public List<OrderEntity> queryUserOrderListByOrderSns(String memberId, List<String> orderSns) {
        LambdaUpdateWrapper<OrderEntity> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(OrderEntity::getMemberId, memberId)
                .in(OrderEntity::getOrderSn, orderSns);
        return list(wrapper);
    }

    @Override
    @Transactional
    public void updateStatusAndPayType(String orderSn, int status, String payType) {
        LambdaUpdateWrapper<OrderEntity> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(OrderEntity::getOrderSn, orderSn)
                .set(OrderEntity::getStatus, status)
                .set(OrderEntity::getPayType, payType)
                .set(OrderEntity::getPaymentTime, LocalDateTime.now());
        update(wrapper);
    }

    private LambdaQueryWrapper<OrderEntity> getWrapper(OrderManageQuery query) {
        LambdaQueryWrapper<OrderEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderEntity::getMemberId, authTokenService.getMemberInfo().getMemberId())
                .eq(StringUtils.isNotEmpty(query.getOrderSn()), OrderEntity::getOrderSn, query.getOrderSn())
                .eq(!Objects.isNull(query.getOrderState()),OrderEntity::getStatus, query.getOrderState())
                .orderByDesc(OrderEntity::getCreateTime);
        return wrapper;
    }
}